package com.itfreer.data.config;

import com.itfreer.data.SysDatabaseHelper;
import com.itfreer.utils.config.ConfigManager;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

/**
 * 配置服务
 */
public class ConfigService {

    public static final ConfigService instance = new ConfigService();
    private ConfigService(){
    }

    /**
     * 初始化配置
     */
    public void init(){
        ConfigEntity entity = getConfig();
        if(entity==null){
            entity = new ConfigEntity();
            entity.setG3DataUpload(false);
            entity.setG3LocalUpload(true);
            entity.setHttpUrl("http://10.0.2.2:9090/development");
            entity.setId(UUID.randomUUID().toString());
            entity.setJwt("");
            entity.setTgt("");

            Dao<ConfigEntity, String> dao = null;
            try {
                dao = SysDatabaseHelper.getInstance().getDao(ConfigEntity.class);
                dao.create(entity);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        ConfigManager.setConfig("HttpUrl", entity.getHttpUrl());
        ConfigManager.setConfig("G3DataUpload", entity.getG3DataUpload());
        ConfigManager.setConfig("G3LocalUpload", entity.getG3LocalUpload());
        ConfigManager.setConfig("jwt", entity.getJwt());
        ConfigManager.setConfig("tgt", entity.getTgt());
    }

    /**
     * 根据ConfigManager更新配置
     */
    public void update(){
        ConfigEntity entity = getConfig();
        if(entity==null){
            return;
        }

        entity.setG3DataUpload((Boolean)ConfigManager.getConfig("G3DataUpload"));
        entity.setG3LocalUpload((Boolean)ConfigManager.getConfig("G3LocalUpload"));
        entity.setHttpUrl(ConfigManager.getConfig("HttpUrl").toString());
        entity.setJwt(ConfigManager.getConfig("jwt").toString());
        entity.setTgt(ConfigManager.getConfig("tgt").toString());

        Dao<ConfigEntity, String> dao = null;
        try {
            dao = SysDatabaseHelper.getInstance().getDao(ConfigEntity.class);
            dao.update(entity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取配置信息
     * @return
     */
    public ConfigEntity getConfig(){
        Dao<ConfigEntity, String> dao = null;
        try {
            dao = SysDatabaseHelper.getInstance().getDao(ConfigEntity.class);
            List<ConfigEntity> entitys = dao.queryForAll();
            ConfigEntity entity = null;
            if(entitys!=null && entitys.size()>0){
                entity = entitys.get(0);
            }
            return entity;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
